package cn.ecnu.user.util;


import cn.ecnu.common.Constant;
import cn.ecnu.exception.RRXException;
import cn.ecnu.user.config.AlipayProperties;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipaySystemOauthTokenRequest;
import com.alipay.api.response.AlipaySystemOauthTokenResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.net.URLEncoder;

@Component
public class AuthSolver {

    @Autowired
    private AlipayProperties properties;

    @Autowired
    private AlipayClient alipayClient;

    // 获取支付宝的重定向页面
    public String getRedirectUrl() {
        return "https://openauth.alipay.com/oauth2/publicAppAuthorize.htm?app_id="
                + properties.getAppId()
                + "&scope=auth_user"
                + "&redirect_uri="
                + URLEncoder.encode(properties.getRedirectUri());
    }


    public String solve(String authCode) {

        if (authCode == null) throw new RRXException(Constant.AUTH_CANCEL.getMsg(), Constant.AUTH_CANCEL.getCode());
        AlipaySystemOauthTokenRequest request = new AlipaySystemOauthTokenRequest();
        // 如果获得的授权码为空
        request.setCode(authCode);
        request.setGrantType("authorization_code");
        AlipaySystemOauthTokenResponse response = null;
        try {
            response = alipayClient.execute(request);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        if (response == null) throw new RRXException(Constant.AUTH_ERROR.getMsg(), Constant.AUTH_ERROR.getCode());
        String userId = response.getUserId();
        if (userId == null) throw new RRXException(Constant.AUTH_TIMEOUT.getMsg(), Constant.AUTH_TIMEOUT.getCode());
        return userId;
    }
}
